package com.waikuai.shop.controller;

import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.dto.StatisticsQueryDTO;
import com.waikuai.shop.service.StatisticsService;
import com.waikuai.shop.vo.CategoryDistributionVO;
import com.waikuai.shop.vo.OrderTrendVO;
import com.waikuai.shop.vo.SalesRankingVO;
import com.waikuai.shop.vo.StatisticsOverviewVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 统计控制器
 * @author waikuai
 */
@Slf4j
@RestController
@RequestMapping("/statistics")
@RequiredArgsConstructor
public class StatisticsController {

    private final StatisticsService statisticsService;

    /**
     * 获取概览统计数据
     * @param timeRange 时间范围：TODAY, WEEK, MONTH, YEAR
     */
    @GetMapping("/overview")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<StatisticsOverviewVO> getOverviewStatistics(
            @RequestParam(defaultValue = "WEEK") String timeRange) {
        try {
            StatisticsQueryDTO.TimeRange range = StatisticsQueryDTO.TimeRange.valueOf(timeRange.toUpperCase());
            StatisticsOverviewVO overview = statisticsService.getOverviewStatistics(range);
            return Result.success(overview);
        } catch (IllegalArgumentException e) {
            log.error("无效的时间范围参数: {}", timeRange);
            return Result.error("无效的时间范围参数");
        } catch (Exception e) {
            log.error("获取概览统计数据失败: {}", e.getMessage(), e);
            return Result.error("获取概览统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单趋势数据
     * @param timeRange 时间范围：TODAY, WEEK, MONTH, YEAR
     */
    @GetMapping("/order-trend")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<OrderTrendVO>> getOrderTrend(
            @RequestParam(defaultValue = "WEEK") String timeRange) {
        try {
            StatisticsQueryDTO.TimeRange range = StatisticsQueryDTO.TimeRange.valueOf(timeRange.toUpperCase());
            List<OrderTrendVO> trend = statisticsService.getOrderTrend(range);
            return Result.success(trend);
        } catch (IllegalArgumentException e) {
            log.error("无效的时间范围参数: {}", timeRange);
            return Result.error("无效的时间范围参数");
        } catch (Exception e) {
            log.error("获取订单趋势数据失败: {}", e.getMessage(), e);
            return Result.error("获取订单趋势数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取销售趋势数据（与订单趋势相同）
     * @param timeRange 时间范围：TODAY, WEEK, MONTH, YEAR
     */
    @GetMapping("/sales-trend")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<OrderTrendVO>> getSalesTrend(
            @RequestParam(defaultValue = "WEEK") String timeRange) {
        try {
            StatisticsQueryDTO.TimeRange range = StatisticsQueryDTO.TimeRange.valueOf(timeRange.toUpperCase());
            List<OrderTrendVO> trend = statisticsService.getOrderTrend(range);
            return Result.success(trend);
        } catch (IllegalArgumentException e) {
            log.error("无效的时间范围参数: {}", timeRange);
            return Result.error("无效的时间范围参数");
        } catch (Exception e) {
            log.error("获取销售趋势数据失败: {}", e.getMessage(), e);
            return Result.error("获取销售趋势数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取分类销售分布
     * @param timeRange 时间范围：TODAY, WEEK, MONTH, YEAR
     */
    @GetMapping("/category-distribution")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<CategoryDistributionVO>> getCategoryDistribution(
            @RequestParam(defaultValue = "WEEK") String timeRange) {
        try {
            StatisticsQueryDTO.TimeRange range = StatisticsQueryDTO.TimeRange.valueOf(timeRange.toUpperCase());
            List<CategoryDistributionVO> distribution = statisticsService.getCategoryDistribution(range);
            return Result.success(distribution);
        } catch (IllegalArgumentException e) {
            log.error("无效的时间范围参数: {}", timeRange);
            return Result.error("无效的时间范围参数");
        } catch (Exception e) {
            log.error("获取分类销售分布失败: {}", e.getMessage(), e);
            return Result.error("获取分类销售分布失败: " + e.getMessage());
        }
    }

    /**
     * 获取商品销售排行
     * @param timeRange 时间范围：TODAY, WEEK, MONTH, YEAR
     * @param limit 查询数量限制
     */
    @GetMapping("/top-products")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<List<SalesRankingVO>> getTopProducts(
            @RequestParam(defaultValue = "WEEK") String timeRange,
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            StatisticsQueryDTO.TimeRange range = StatisticsQueryDTO.TimeRange.valueOf(timeRange.toUpperCase());
            List<SalesRankingVO> rankings = statisticsService.getTopProducts(range, limit);
            return Result.success(rankings);
        } catch (IllegalArgumentException e) {
            log.error("无效的时间范围参数: {}", timeRange);
            return Result.error("无效的时间范围参数");
        } catch (Exception e) {
            log.error("获取商品销售排行失败: {}", e.getMessage(), e);
            return Result.error("获取商品销售排行失败: " + e.getMessage());
        }
    }
}

